package cn.latsen.springboot.entities;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Configuration;

import java.util.HashSet;
import java.util.Set;
@Configuration
public class Relam extends AuthorizingRealm {
//授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("————权限认证————");
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得该用户角色
        String role = "user";
        Set<String> set = new HashSet<>();
        //需要将 role 封装到 Set 作为 info.setRoles() 的参数
        set.add(role);
        //设置该用户拥有的角色
        info.setRoles(set);
        return info;

    }
//验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
        String password="123";
        String name="冯科";
        String passFromToken=new String( (char[]) usernamePasswordToken.getCredentials());
        String nameFromToken=usernamePasswordToken.getUsername();
        if (!name.equals(nameFromToken))
        {
            throw new AccountException("你的用户名错误");

        }
        if (!passFromToken.equals(password))
        {
            throw new AccountException("你的密码错误");
        }

        return new SimpleAuthenticationInfo(usernamePasswordToken.getPrincipal(),usernamePasswordToken.getPassword(),usernamePasswordToken.getUsername());
    }
}
